package com.edu.zju.scs.panacea.mapper.resource;

import com.edu.zju.scs.panacea.entity.resource.Template;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: Yue Liang
 * @Date: 2018-12-19 18:24
 */
@Repository
public interface TemplateMapper {

    @Select("SELECT * FROM res_template WHERE id = #{id}")
    @Results(id="templateMap", value={
            @Result(id=true,property="id",column="id"),
            @Result(property="siteId",column="site_id"),
            @Result(property="type",column="type"),
            @Result(property="name",column="name"),
            @Result(property="maxSize",column="maxSize"),
            @Result(property="height",column="height"),
            @Result(property="width",column="width"),
            @Result(property="format",column="format", typeHandler = com.edu.zju.scs.panacea.utils.JsonTypeHandler.class)})
    Template selectTemplate(Long id);

    @Select("SELECT * FROM res_template WHERE site_id = #{siteId}")
    @ResultMap(value = "templateMap")
    List<Template> selectTemplateBySiteId(Long siteId);


    @Select({ "<script>",
            "SELECT DISTINCT * FROM res_template WHERE type = #{type} and id in (select template_id from res_template_rel_loc where loc_id in " ,
                    " <foreach collection=\"list\" index=\"index\" item=\"item\" open=\"(\" separator=\",\" close=\")\">",
                    "   #{item} " ,
                    " </foreach>)" ,
            "</script>"})
    @ResultMap(value = "templateMap")
    List<Template> selectTemplateByLocs(@Param("list") List<Long> locIds, @Param("type") Integer type);



    @Select("SELECT * FROM res_template")
    @ResultMap(value = "templateMap")
    List<Template> selectAllTemplate();

    @Delete("DELETE FROM res_template where id = #{id}")
    long deleteTemplate(Long id);

    @Insert("INSERT INTO res_template(site_id, type, name, maxSize, height, width, format)" +
            " VALUES(#{siteId}, #{type}, #{name}, #{maxSize}, #{height}, #{width}, #{format, typeHandler=com.edu.zju.scs.panacea.utils.JsonTypeHandler})")
    @Options(useGeneratedKeys=true)
    long insertTemplate(Template template);

    @Update({ "update res_template set site_id = #{siteId}, type = #{type}, name = #{name}, maxSize = #{maxSize}," +
            " height = #{height}, width = #{width}, format = #{format, typeHandler=com.edu.zju.scs.panacea.utils.JsonTypeHandler} where id = #{id}" })
    long updateTemplate(Template template);


}
